package com.mediacloud.app.newsmodule.fragment.audio.live;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import com.mediacloud.app.model.view.RecyclerViewHF;

/**
 * Created by anonymous on 2016/9/9 0009.
 * <p>
 * GridSpacingItemDecoration
 * <p>
 * int mSpanCount = 3; // 3 columns
 * int spacing = 50; // 50px
 * boolean includeEdge = false;
 * recyclerView.addItemDecoration(new GridSpacingItemDecoration(mSpanCount, spacing, includeEdge));
 */
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int mSpanCount;//横条目数量
    private int mRowSpacing;//行间距
    private int mColumnSpacing;// 列间距
    private boolean includeEdge;//是否包含边缘

    public GridSpacingItemDecoration(int spanCount, int rowSpacing, int columnSpacing, boolean includeEdge) {
        this.mSpanCount = spanCount;
        this.mRowSpacing = rowSpacing;
        this.mColumnSpacing = columnSpacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position

        try {
            if (parent instanceof RecyclerViewHF){
                position = position-((RecyclerViewHF)parent).getHeadersCount();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        if (position<0){
            return;
        }
        int column = position % mSpanCount; // item column

        if (includeEdge) {
            outRect.left = mColumnSpacing - column * mColumnSpacing / mSpanCount; // mColumnSpacing - column * ((1f / mSpanCount) * mColumnSpacing)
            outRect.right = (column + 1) * mColumnSpacing / mSpanCount; // (column + 1) * ((1f / mSpanCount) * mColumnSpacing)

            if (position < mSpanCount) { // top edge
                outRect.top = mRowSpacing;
            }
            outRect.bottom = mRowSpacing; // item bottom
        } else {
            outRect.left = column * mColumnSpacing / mSpanCount; // column * ((1f / mSpanCount) * mColumnSpacing)
            outRect.right = mColumnSpacing - (column + 1) * mColumnSpacing / mSpanCount; // mColumnSpacing - (column + 1) * ((1f /    mSpanCount) * mColumnSpacing)
            if (position >= mSpanCount) {
                outRect.top = mRowSpacing; // item top
            }
        }
    }
}